package com.jws.battleship;

import java.util.ArrayList;
import java.util.zip.DataFormatException;

import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Color;
import android.os.Bundle;
import android.view.View;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.LinearLayout;
import android.widget.ListView;

public class HomeActivity extends Activity 
{
	public final static int idPrefs = 0;
	private HomeMenuBackground mMenuBackground;
	private Boolean mIsMenuUp;
	private Boolean mIsNewBattlePushed;
	private NetworkInterface NI;
	private Boolean mResetMenu = false;
	
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.home);
        
        mMenuBackground = (HomeMenuBackground)findViewById(R.id.home_menu_background);
        animateShips();
        
        if(savedInstanceState == null)
        {
        	mIsMenuUp = false;
        	mIsNewBattlePushed = false;
        }
        
        else
        {
        	mIsMenuUp = savedInstanceState.getBoolean(getString(R.string.savedInstanceState_home_isMenuUp));
        	mIsNewBattlePushed = savedInstanceState.getBoolean(getString(R.string.savedInstanceState_home_isNewBattlePushed));
        	
        	if(mIsMenuUp)
        	{
        		restoreSettings();
        	}
        	
        	else if(mIsNewBattlePushed)
        	{
        		restoreNewBattlePushed();
        	}
        }
        
        createActiveGameList();
        
        
    }
    
    private void createActiveGameList()
    {
    	ArrayList<Game> listOfGames = getSavedGamesFromDatabase();
		
		ListView list = (ListView)findViewById(R.id.home_list_active_games);
		list.setCacheColorHint(Color.TRANSPARENT);
		list.setSelector(R.drawable.transparent);
		
		//Adding footer
		View header = (View)getLayoutInflater().inflate(R.layout.active_game_list_header, null);
		list.addHeaderView(header, null, false);
		
		//Adding footer
		View footer = (View)getLayoutInflater().inflate(R.layout.active_game_list_footer, null);
		list.addFooterView(footer, null, false);
		 
        // Getting adapter by passing xml data ArrayList
		ActiveGameAdapter adapter= new ActiveGameAdapter(this, R.layout.active_game_list_row, listOfGames);
        list.setAdapter(adapter);
 
        // Click event for single list row
        list.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				// TODO Auto-generated method stub
				
			}});
        
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_HARDWARE_ACCELERATED, WindowManager.LayoutParams.FLAG_HARDWARE_ACCELERATED);
        
        
        
        //Boolean test = list.isHardwareAccelerated();
        
        
        
    }
    
    @Override
    protected void onResume() {
    	if(mResetMenu)
    	{
    		hideCreateOrJoinMenu();
    		mResetMenu = false;
    		mIsMenuUp = false;
    		mIsNewBattlePushed = false;
    	}
    	super.onResume();
    }
    
    private void animateShips()
    {
        Animation translate = AnimationUtils.loadAnimation(getApplicationContext(), R.anim.float_to_right_full_screen);
    	findViewById(R.id.home_animation_ship1).startAnimation(translate);
    }
    
    private void animateSettingsIcon()
    {
    	Animation rotate = AnimationUtils.loadAnimation(getApplicationContext(), R.anim.rotate_center_360);
    	findViewById(R.id.home_icon_settings).startAnimation(rotate);
    }
    
    private void animateBasketIcon()
    {
    	Animation gogo = AnimationUtils.loadAnimation(getApplicationContext(), R.anim.go_go_basket);
    	findViewById(R.id.home_icon_store).startAnimation(gogo);
    }
    
    public void playClicked(View view)
    {
    	showCreateOrJoinMenu();
    	
    	//Intent intent = new Intent(this, FriendListActivity.class);
    	//startActivity(intent);
    }

    public void settingsClicked(View view)
    {    	
    	autoShowHideSettings();
    }
    
    public void createClicked(View view)
    {   
    	mResetMenu = true;
    	Intent intent = new Intent(this, NetworkFactoryActivity.class);
    	intent.putExtra(getString(R.string.NetworkFactoryNewNetwork), getString(R.string.NetworkFactoryCreateGame));
    	startActivityForResult(intent, getResources().getInteger(R.integer.NetworkFactoryRequestBluetoothCode));
    }
    
    public void storeClicked(View view)
    {
    	animateBasketIcon();
    	
    	Game myGame = new Game();
    	myGame.setTurn("Your turn");
    	
    	Coordinate shot1 = new Coordinate("4,3");
    	Coordinate shot2 = new Coordinate("5,6");
    	Coordinate shot3 = new Coordinate("8,2");
    	Coordinate shot4 = new Coordinate("10,1");
    	
    	Coordinate ship1Start = new Coordinate("4,2");
    	Coordinate ship2Start = new Coordinate("5,10");
    	Coordinate ship3Start = new Coordinate("1,6");
    	Coordinate ship1Direction = new Coordinate("1,1");
    	Coordinate ship2Direction = new Coordinate("0,-1");
    	Coordinate ship3Direction = new Coordinate("1,-1");
    	
    	
    	Ship ship1 = new Ship();
    	Ship ship2 = new Ship();
    	Ship ship3 = new Ship();
    	
    	try 
    	{
			ship1.setType(Ship.TYPE_NORMAL);
			ship1.setDirection(ship1Direction);
			ship1.setStartPosition(ship1Start);
			
			ship2.setType(Ship.TYPE_SMALL);
			ship2.setDirection(ship2Direction);
			ship2.setStartPosition(ship2Start);
			
			ship3.setType(Ship.TYPE_BIG);
			ship3.setDirection(ship3Direction);
			ship3.setStartPosition(ship3Start);
		}
    	
    	catch (DataFormatException e) 
    	{
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
    	
    	ArrayList<Ship> myShips = new ArrayList<Ship>();
    	ArrayList<Ship> oppShips = new ArrayList<Ship>();
    	myShips.add(ship1);
    	myShips.add(ship2);
    	oppShips.add(ship3);
    	oppShips.add(ship2);
    	
    	myGame.setMyShips(myShips);
    	myGame.setOpponentsShips(oppShips);
    	
    	Friend friend = new Friend();
    	friend.setName("The ONE");
    	friend.setUniqueID(1); //TODO ID'et skal sættes før spillet gemmes. Derfor kan det være jeg bliver nød til at lave en relation mellem tabellerne.
    	
    	ArrayList<Friend> friends = new ArrayList<Friend>();
    	friends.add(friend);
    	
    	myGame.setOpponents(friends);
    	
    	ArrayList<Coordinate> shots = new ArrayList<Coordinate>();
    	shots.add(shot1);
    	shots.add(shot2);
    	shots.add(shot3);
    	shots.add(shot4);
    	
    	myGame.setShots(shots);
    	
    	
    	DBSavedGames db = new DBSavedGames(getApplicationContext());
    	db.open();
    	
    	//db.insertFriend(friend);   	
    	db.insertGame(myGame);
    	
    	db.close();
    }
    
    public void startLocalOriginalGameClicked(View view)
    {
    	Intent intent = new Intent(this, BattleActivity.class);
    	startActivity(intent);
    }
    
    private void autoShowHideSettings()
    {
    	if(mIsMenuUp)
    	{
    		hideSettings();
    		animateSettingsIcon();
    	}
    	
    	else
    	{
    		showSettings();
    	}
    }
    
    private void showSettings()
    {
		mMenuBackground.makeBig();
		mIsMenuUp = true;
    }
    
    private void hideSettings()
    {
    	mMenuBackground.makeSmall();
		mIsMenuUp = false;
		animateSettingsIcon();
    }
    
    private void showCreateOrJoinMenu()
    {
    	((LinearLayout)findViewById(R.id.home_menu_content)).setVisibility(LinearLayout.GONE);    	
    	((LinearLayout)findViewById(R.id.home_menu_join_create)).setVisibility(LinearLayout.VISIBLE);
    	mIsNewBattlePushed = true;
    }
    
    private void hideCreateOrJoinMenu()
    {
    	((LinearLayout)findViewById(R.id.home_menu_content)).setVisibility(LinearLayout.VISIBLE);    	
    	((LinearLayout)findViewById(R.id.home_menu_join_create)).setVisibility(LinearLayout.GONE);
    	mIsNewBattlePushed = false;
    }
    
    private void restoreSettings()
    {
    	if(mIsMenuUp)
    	{
    		mMenuBackground.makeBig();
    		mIsMenuUp = true;
    	}
    	
    	else
    	{
    		mMenuBackground.makeSmall();
    		mIsMenuUp = false;
    	}
    }
    
    private void restoreNewBattlePushed()
    {
    	if(mIsNewBattlePushed)
    	{
    		showCreateOrJoinMenu();
    	}
    	
    	else
    	{
    		hideCreateOrJoinMenu();
    	}
    }
    
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) 
    {
    	super.onActivityResult(requestCode, resultCode, data);
    	if(requestCode == idPrefs)
    	{
    		animateSettingsIcon();
    	}
    	else if(requestCode == getResources().getInteger(R.integer.NetworkFactoryRequestBluetoothCode)) 
    	{
    		try {
				NI = NetworkInterface.getInstance();
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
    	}

    }
    
    @Override
    protected void onSaveInstanceState(Bundle outState) 
    {
    	outState.putBoolean(getString(R.string.savedInstanceState_home_isMenuUp), mIsMenuUp);
    	outState.putBoolean(getString(R.string.savedInstanceState_home_isNewBattlePushed), mIsNewBattlePushed);
    	
    	super.onSaveInstanceState(outState);
    }
    
    @Override
    public void onBackPressed() {
    	if(mIsNewBattlePushed)
    	{
    		hideCreateOrJoinMenu();
    	}
    	
    	else if(mIsMenuUp)
    	{
    		hideSettings();
    	}
    	
    	else
    		super.onBackPressed();
    }
    
    public void joinGame(View v)
    {
    	mResetMenu = true;
    	Intent intent = new Intent(this, NetworkFactoryActivity.class);
    	intent.putExtra(getString(R.string.NetworkFactoryNewNetwork), getString(R.string.NetworkFactoryJoinGame));
    	startActivity(intent);
    }
    
    private ArrayList<Game> getSavedGamesFromDatabase()
    {
    	ArrayList<Game> games = new ArrayList<Game>();
    	
    	DBSavedGames db = new DBSavedGames(getApplicationContext());
    	
    	db.open();
    	Cursor result = db.getAllItemsCursor();
    	
    	for (int i = 0; i < result.getCount(); i++) 
    	{
    		result.moveToPosition(i);
    		Game myGame = new Game();
    		
    		String test = result.getString(DBSavedGames.GAME_TABLE_OPPONENTS);
    		
			myGame.setCreatedDate(result.getString(DBSavedGames.GAME_TABLE_CREATED));
			myGame.setTurn(result.getString(DBSavedGames.GAME_TABLE_TURN));
    		myGame.setOpponents(Friend.stringToFriendList(test, getApplicationContext()));
    		
    		games.add(myGame);
		}
    	
    	db.close();
    	
    	return games;
    }
}
